import React, { Component } from 'react';
import { Form, Input,Modal,message,Upload,Button,Icon,Cascader} from 'antd';
import axios from 'axios';
import qs from 'qs';

const FormItem = Form.Item;
const formItemLayout = {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 },
};

class alertModal extends Component {

        constructor(props) {
                super(props);
                //console.log(props)
                console.log("zz")
                this.state= {
                        list:[],
                        previewVisible: false,
                        previewImage: '',
                        fileList: []
                }
        }
        //第二次以后打开 保证获取props
        componentWillReceiveProps(nextProps){
                console.log(nextProps)
                console.log(this.props.record==nextProps.record)
                //if(!this.props.record==nextProps.record)
                //{
                        this.setState({ fileList: [nextProps.record.imgurl]})
                //}

        }
        componentDidMount() {
                this.getClassList()
        }
        getClassList = () => {
                let that=this
                axios.post("/api/?s=Newsclass.getTree")
                    .then(function (response) {
                            let result=response.data.data
                            that.setState(
                                {
                                        list:result.items
                                }
                            )
                    })
                    .catch(function (error) {
                            console.log(error);
                    })
        }

        handleOk = (e) => {
                console.log(e);
                e.preventDefault();
                this.props.form.validateFields((err, values) => {
                        if (!err) {
                                console.log('Received values of form: ', values);
                                let formData=values
                                if(this.props.record.actionType==="mod")
                                {
                                        formData.id=this.props.record.id
                                }
                                console.log(formData)
                                //在此处构造提交数据
                                let sendJson=formData
                                     sendJson.fatheridArr=sendJson.fatheridArr.toString()
                                     sendJson.imgurl=JSON.stringify(this.state.fileList)
                                let sendString=qs.stringify(sendJson)
                                if(this.props.record.actionType==="add")
                                {
                                        this.insertRecord(sendString)
                                }
                                else
                                {
                                        this.updateRecord(sendString)
                                }
                        }
                });
        }
        insertRecord=(sendJson)=>{
                let that=this
                axios.post("/api/?s=Newsclass.insert",sendJson)
                    .then(function (response) {
                            let result=response.data
                            if(result.ret===200)
                            {
                               that.handleCancel()
                               that.props.refresh()
                               message.success("添加成功！")
                            }
                            else
                            {
                               message.error(result.msg)
                            }

                    })
                    .catch(function (error) {
                            console.log(error);
                    })
        }

        updateRecord=(sendJson)=>{
                let that=this
                axios.post("/api/?s=Newsclass.update",sendJson)
                    .then(function (response) {
                            let result=response.data
                            if(result.ret===200)
                            {
                                    that.handleCancel()
                                    that.props.refresh()
                                    message.success("修改成功！")
                            }
                            else
                            {
                                    message.error(result.msg)
                            }

                    })
                    .catch(function (error) {
                            console.log(error);
                    })
        }

        handleCancel = (e) => {
                console.log(e);
                this.props.changeStatus()
        }
        handleUploadCancel = () => this.setState({ previewVisible: false })

        handleUploadPreview = (file) => {
                this.setState({
                        previewImage: file.url || file.thumbUrl,
                        previewVisible: true,
                });
        }

        handleUploadChange = ({ fileList }) => {
                console.log(fileList)
                //status uploading 上传中 done 上传完整
                if(fileList.length>0 && fileList[fileList.length-1].status=="done")
                {
                        console.log(fileList[fileList.length-1].response.data)
                        //当多余一张图片时 将多余的图片删除
                        if(fileList.length>=2)
                        {
                                fileList.splice(0,1)
                        }

                        this.setState({fileList: fileList[fileList.length-1].response.data})
                }
                else
                {
                        this.setState({fileList: []})
                }

        }
        beforeUpload=(file, fileList) => {
                // 检查图片类型
                // 只能上传三种图片格式
                //const isJPG = file.type === 'image/jpeg';
                //const isPNG = file.type === 'image/png';
                //const isBMP = file.type === 'image/bmp';
                //const isGIF = file.type === 'image/gif';
                //const isWEBP = file.type === 'image/webp';
                //const isPic = isJPG || isPNG || isBMP || isGIF || isWEBP;
                //if (!isPic) {
                //        message.error('只能上传图片');
                //        this.setState({
                //                fileListD: fileList.filter((fileItem)=> file.uid !== fileItem.uid),
                //        });
                //        return false;
                //}
                //return isPic;
                return true
        };

        render() {
                const { getFieldDecorator } = this.props.form;
                return (
                    <div>
                            <Modal
                                title={this.props.record.actionType==="add"?"新增":"修改"}
                                visible={this.props.viewModal}
                                onOk={this.handleOk}
                                okText={"确定"}
                                cancelText={"取消"}
                                onCancel={this.handleCancel}
                                destroyOnClose
                            >
                                    <Form>
                                            <FormItem {...formItemLayout} label="分类名称">
                                                    {getFieldDecorator('classname', {
                                                            rules: [{
                                                                    required: true,
                                                                    message: '请输入分类名称',
                                                            }],
                                                    })(
                                                        <Input placeholder="请输入用户名"/>
                                                    )}
                                            </FormItem>
                                            {JSON.stringify(this.state.fileList)}
                                            <div className="ant-row ant-form-item">
                                                    <div className="ant-col-5 ant-form-item-label"><label className="ant-form-item-required" >图片上传</label></div>
                                                    <div className="ant-col-18 ant-form-item-control-wrapper">
                                                            <div className="ant-form-item-control">
                                                                    <span className="ant-form-item-children">
                                                                           <Upload name="file" action="/api/?s=App.Examples_Upload.go"
                                                                                   showUploadList={true}
                                                                                   defaultFileList={this.state.fileList}
                                                                                   onPreview={this.handleUploadPreview}
                                                                                   onChange={this.handleUploadChange}
                                                                                   beforeUpload={this.beforeUpload}
                                                                                   listType="picture">
                                                                                   <Button>
                                                                                           <Icon type="upload" /> 点击上传图片
                                                                                   </Button>
                                                                           </Upload>
                                                                            <Modal visible={this.state.previewVisible} footer={null} onCancel={this.handleUploadCancel}>
                                                                                    <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
                                                                            </Modal>
                                                                    </span>
                                                            </div>
                                                    </div>
                                            </div>
                                            <FormItem
                                                {...formItemLayout}
                                                label="父级目录"
                                            >
                                                    {getFieldDecorator('fatheridArr', {
                                                            initialValue: [],
                                                            rules: [{ type: 'array', required: true, message: '请选择父级目录' }],
                                                    })(
                                                        <Cascader options={this.state.list} />
                                                    )}
                                            </FormItem>
                                            <FormItem {...formItemLayout} label="排序编号">
                                                    {getFieldDecorator('orderNo', {
                                                            rules: [{
                                                                    required: true,
                                                                    message: '请输入排序编号',
                                                            }],
                                                    })(
                                                        <Input placeholder="请输入排序编号"/>
                                                    )}
                                            </FormItem>
                                        </Form>
                            </Modal>
                    </div>
                );
        }
}
export default Form.create({
        mapPropsToFields(props) {
                return {
                        classname: Form.createFormField({
                                value: props.record.classname,
                        }),
                        fatheridArr: Form.createFormField({
                                value: props.record.fatheridArr,
                        }),
                        orderNo: Form.createFormField({
                                value: props.record.orderNo,
                        }),
                };
        },
})(alertModal)